package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import modal.ProductModal;
import modal.UserModal;
import dao.BidsDAO;

/**
 * Servlet implementation class AddBidController
 */
@WebServlet("/AddBidController")
public class AddBidController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddBidController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			doProcess(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			doProcess(request, response);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doProcess(HttpServletRequest request,
			HttpServletResponse response) throws NumberFormatException,
			Exception {
		BidsDAO bdao = new BidsDAO();
		HttpSession session = request.getSession();
		ProductModal prod = (ProductModal) session.getAttribute("prod");
		UserModal user = new UserModal();
		if (session.getAttribute("user") != null) {
			user = (UserModal) session.getAttribute("user");
		} else {
			response.sendRedirect("/BidMarket/login.jsp");
		}
		int status = 0;
		if (user.getEmail() == session.getAttribute("sellerEmail")) {
			status = 1;
		}
		bdao.AddBid(prod.getProductId(), user.getUserId(),
				Integer.parseInt(request.getParameter("inputBid").toString()),
				status);
		request.getRequestDispatcher("/HomeController").forward(request, response);
	}

}
